<?php
/**
 * Created by JetBrains PhpStorm.
 * User: 蒋文书
 * Date: 14-12-27
 * Time: 下午11:27
 * To change this template use File | Settings | File Templates.
 */

namespace Admin\Controller;
use Think\Controller;


class UserController extends CommonController{

    /**
     * 用户列表
     * @author jiangwenshu <jiangwenshu1990@126.com>
     */
    public function index(){  
        $this->list = D('User')->relation('role')->select();   
        $this->meta_title = '用户列表';
        $this->display();
    }

    /**
     * 新增用户
     * @author jiangwenshu <jiangwenshu1990@126.com>
     */
    public function add(){
        //显示角色角色
        $this->list = M('role')->select();
        if(IS_POST){
            //获取用户信息
            $data = array(
                'username'=> I('username'),
                'password'=> I('password','','md5'),
                'reg_time'=>time(),
                'reg_ip'=> get_client_ip(),
                );
            $role =array();
            //添加所属角色
            if($uid=M('user')->add($data)){
                 $role=array(
                        'role_id'=> I('role'),
                        'user_id'=> $uid
                    );
                 M('role_user')->add($role);
                $this->success('新增成功！',U('Index'));
            }else{
                 $this->error('新增失败！');
            }
        }
        $this->meta_title = '新增用户';
        $this->display();
    }

    /**
     * 删除用户
     * @author jiangwenshu <jiangwenshu1990@126.com>
     */
    public function del(){  
        $id =I('id',0,'intval');
        if(D('user')->del($id)){
            $this->success('删除成功',U('Index'));
        }else{
            $this->error('删除失败！');
        }
    }

    /**
     * 新增用户
     * @author jiangwenshu <jiangwenshu1990@126.com>
     */
    public function edit(){
        //显示角色角色
        $this -> list = M('role')->select();
        $id =I('id',0,'intval');
        $password=I('password');
        $role=I('role');
        if(IS_POST){
            empty($password) && $this->error('密码不能为空！');
            if(D('User')->update($data)){
                if($role){
                    M('role_user')->where(array('user_id'=>$id))->delete();
                    $role=array(
                            'role_id'=> $role,
                            'user_id'=> $id
                    );
                    M('role_user')->add($role);
                }
                $this->success('更新成功！',U('Index'));
            }else{
                $this->error('更新失败！');
            }
        }else{
            $this->info=D('User')->info($id);
        } 
        $this->meta_title = '编辑用户';
        $this->display();
    }  
} 
